﻿using AutoMapper;
using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Darius.API.Application.Commands
{
    public class RolePermissionSearchHandler : IRequestHandler<RolePermissionSearchCommand, Result>
    {
        private readonly IBaseRepositorys<RolesPermission> rolePermissionRepository;
        private readonly IMapper mapper;
        private readonly IBaseRepositorys<Roles> roleRepository;
        private readonly IBaseRepositorys<Permission> permissionRepository;
        private readonly ILogger<RolePermissionSearchHandler> logger;

        public RolePermissionSearchHandler(IBaseRepositorys<RolesPermission> rolePermissionRepository, IMapper mapper, IBaseRepositorys<Roles> roleRepository, IBaseRepositorys<Permission> permissionRepository, ILogger<RolePermissionSearchHandler> logger)
        {
            this.rolePermissionRepository = rolePermissionRepository;
            this.mapper = mapper;
            this.roleRepository = roleRepository;
            this.permissionRepository = permissionRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 查询角色权限
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(RolePermissionSearchCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CodeEnum.search };
                var list = from a in rolePermissionRepository.GetAll()
                           join b in roleRepository.GetAll() on a.RoleId equals b.RoleId
                           join c in permissionRepository.GetAll() on a.PermissionId equals c.PermissionsId
                           group new { b, c } by new { b.RoleName, b.RoleId } into e
                           select new RolePermissDto
                           {
                               RoleName = e.Key.RoleName,
                               RoleId = e.Key.RoleId,
                               PermissionName = string.Join(",", e.Select(f => f.c.PermissionsName))

                           };
                result.Data = list.ToList();
                logger.LogInformation("查询成功");
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "查询失败");
                return new Result() { Code = (int)CodeEnum.error, Messege = "查询失败" };               
            }
        }

        
    }
}
